<template>
  <t-table
    row-key="id"
    table-layout="auto"
    :data="payStore.getList()"
    :columns="columns"
    :loading="loading"
    hover
  >
    <template #sort="{ row }">
      <t-tag theme="primary" variant="light">{{ row.sort }}</t-tag>
    </template>
    <template #name="{ row }">
      <b>{{ row.name }}</b>
    </template>
    <template #norm="{ row }">
      <span v-if="row.norm > 0">{{ app.money.format(row.norm) }}</span>
    </template>
    <template #status="{ row }">
      <t-tag :theme="row.status ? 'success' : 'danger'" variant="light">
        {{ plugin.tm('pay.status_text')[row.status] }}
      </t-tag>
    </template>
    <template #right="{ row }">
      <t-button theme="primary" variant="text" @click="() => emit('update', row)">{{ $t('common.update') }}</t-button>
      <t-popconfirm 
        theme="warning" 
        :content="$t('message.confirm.delete')" 
        @confirm="onDelete(row)"
      >
        <t-button theme="warning" variant="text">{{ $t('common.delete') }}</t-button>
      </t-popconfirm>
    </template>
  </t-table>
</template>
<script setup>
  import { ref } from 'vue'
  import app from '@/app'
  import index from '../../index'
  import payStore from '../../store/pay'

  const emit = defineEmits(['delete', 'update'])
  const plugin = index.plugin
  const columns = [{
    title: plugin.t('pay.sort'),
    colKey: 'sort',
    cell: 'sort'
  }, {
    title: plugin.t('pay.name'),
    colKey: 'name',
    cell: 'name'
  }, {
    title: plugin.t('pay.norm'),
    colKey: 'norm',
    align: 'center',
    cell: 'norm'
  }, {
    title: plugin.t('pay.status'),
    colKey: 'status',
    align: 'center',
    cell: 'status'
  }, {
    colKey: 'right',
    align: 'right',
    cell: 'right'
  }]
  
  const loading = ref(true)
  payStore.get().then(res => {
    // 快速创建
    if(res.length == 0) {
      app.confirm({
        theme: 'success',
        header: plugin.t('pay.default_title'),
        body: plugin.t('pay.default_message'),
        confirmBtn: {
          theme: 'success',
          content: app.lang.t('common.create'),
        }
      }, async(hide) => {
        for (let i = 0; i < plugin.tm('pay.default').length; i++) {
          await payStore.update(plugin.tm('pay.default')[i])
        }
        hide()
      })
    }
  }).finally(() => {
    loading.value = false
  })

  // 删除
  const onDelete = row => {
    loading.value = true
    payStore.del(row.id).then(res => {
      app.message('success', 'message.' +  res.message)
    }).catch(res => {
      app.message('error', 'message.error.' + res.message)
    }).finally(() => {
      loading.value = false
    })
  }
</script>